package com.lzy.arithmetic;

/**
 * Author: lzy
 * Date:   2020/06/11 17:36
 * Description:
 **/
public class 环路检测 {

    public static void main(String[] args) {
        ListNode l1 = new ListNode(3);
        ListNode l2 = new ListNode(2);
        ListNode l3 = new ListNode(0);
        ListNode l4 = new ListNode(-1);
        l1.next = l2;
        l2.next = l3;
        l3.next = l4;
        l4.next = l2;

        ListNode node = detectCycle(l1);
        System.out.println(node.val);
    }

    public static ListNode detectCycle(ListNode head) {
        ListNode fast = head;
        ListNode slow = head;
        while (fast != null && fast.next != null) {
            slow = slow.next;
            fast = fast.next.next;
            //快慢指针相遇了，说明有环
            if (slow.val == fast.val) {
                break;
            }
        }
        //快指针走出了边界，说明没有环
        if (fast == null || fast.next == null) {
            return null;
        }
        fast = head;
        while (fast != slow) {
            fast = fast.next;
            slow = slow.next;
        }
        return fast;
    }
}

